//
//  NetworkManager.swift
//  BUYOU
//
//  Created by tyuu on 2024/6/1.
//

import Foundation

// 定义一个 Result 类型来处理网络请求的结果
enum NetworkResult<T> {
    case success(T)
    case failure(Error)
}

// 定义一个 HTTP 方法枚举
enum HTTPMethod: String {
    case get = "GET"
    case post = "POST"
}

class NetworkManager {

    static let shared = NetworkManager()
    private let session: URLSession

    private init() {
        self.session = URLSession(configuration: .default)
    }

    // 生成URLRequest
    private func createRequest(url: URL, method: HTTPMethod, headers: [String: String]?, body: Data?) -> URLRequest {
        var request = URLRequest(url: url)
        request.httpMethod = method.rawValue
        headers?.forEach { key, value in
            request.setValue(value, forHTTPHeaderField: key)
        }
        request.httpBody = body
        return request
    }

    // 处理响应
    private func handleResponse(data: Data?, response: URLResponse?, error: Error?) -> Result<Data, Error> {
        if let error = error {
            return .failure(error)
        }
        
        guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else {
            let statusCode = (response as? HTTPURLResponse)?.statusCode ?? -1
            let error = NSError(domain: "", code: statusCode, userInfo: [NSLocalizedDescriptionKey: "HTTP error: \(statusCode)"])
            return .failure(error)
        }
        
        guard let data = data else {
            let error = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data returned"])
            return .failure(error)
        }
        
        return .success(data)
    }

    // 发送请求
    private func sendRequest(_ request: URLRequest, completion: @escaping (NetworkResult<Data>) -> Void) {
        let task = session.dataTask(with: request) { data, response, error in
            let result = self.handleResponse(data: data, response: response, error: error)
            DispatchQueue.main.async {
                switch result {
                case .success(let data):
                    completion(.success(data))
                case .failure(let error):
                    completion(.failure(error))
                }
            }
        }
        task.resume()
    }

    // GET 请求
    func get(url: URL, headers: [String: String]? = nil, completion: @escaping (NetworkResult<Data>) -> Void) {
        let request = createRequest(url: url, method: .get, headers: headers, body: nil)
        sendRequest(request, completion: completion)
    }

    // POST 请求
    func post(url: URL, headers: [String: String]? = nil, body: Data? = nil, completion: @escaping (NetworkResult<Data>) -> Void) {
        let request = createRequest(url: url, method: .post, headers: headers, body: body)
        sendRequest(request, completion: completion)
    }
}
